// bimface auth
// auth.js
import axios, { AxiosRequestConfig } from 'axios';
import dayjs from 'dayjs';
const ACCESS_TOKEN = 'bimface_access_token';
const EXPIRE_TIME = 'bimface_expire_time';
const HUB_ID = 'bimface_hub_id';
const PROJECT_ID = 'bimface_project_id';
const BIMFACE_AUTH = 'bimface_auth';

// 获取 access token，以及hubId和projectId
async function fetchBimfaceBasicInfo() {
  let accessToken: string | null = localStorage.getItem(ACCESS_TOKEN);
  const expireTime: string | null = localStorage.getItem(EXPIRE_TIME);
  const hubId: string | null = localStorage.getItem(HUB_ID);
  const projectId: string | null = localStorage.getItem(PROJECT_ID);

  // 如果存在未过期的 access token，并且hubId和projectId都存在，则直接返回
  if (hubId && projectId && accessToken && expireTime && !dayjs(expireTime).isBefore(dayjs())) {
    return accessToken;
  }

  // 如果没有 access token 或者已过期，请求新的 access token
  try {
    // TODO 从中台获取bimface的信息
    // const bimfaceBasicInfo = (await getCurrentUserBimfaceKey()).data; // 获取向BIMFACE请求accessToken所需的base64(appKey + ":" + appSecret)字符串
    
    // localStorage.setItem(HUB_ID, '10000000000020001');
    // localStorage.setItem(PROJECT_ID, '10000828810471');
    // localStorage.setItem(
    //   BIMFACE_AUTH,
    //   'cFhDUVJRNHZwOGZ2dmpmVzgyZWJMbGVJR2xxQlZXNjg6dVNZN1hwc01zbWZwbXVJOGI4N2s3MVJhUTVVVVRrYnk=',
    // );

    const options: AxiosRequestConfig = {
      headers: {
        Authorization:
          'Basic ' +
          'cFhDUVJRNHZwOGZ2dmpmVzgyZWJMbGVJR2xxQlZXNjg6dVNZN1hwc01zbWZwbXVJOGI4N2s3MVJhUTVVVVRrYnk=',
        'Content-Type': 'application/json',
      },
    };

    await axios.post('/bimface/oauth2/token', {}, options).then((response) => {
      // 存储新的 access token 和过期时间
      const newAccessToken = response.data.data.token;
      const newExpireTime = response.data.data.expireTime; // YYYY-MM-DD HH:mm:ss
      localStorage.setItem(ACCESS_TOKEN, newAccessToken);
      localStorage.setItem(EXPIRE_TIME, newExpireTime);
      accessToken = newAccessToken;
    });
  } catch (error) {
    console.error('Failed to fetch bimface access token:', error);
    throw error;
  }

  // 返回新获取的 Bimface accessToken
  return accessToken;
}

// 移除 access token
function removeBimfaceAccessToken() {
  localStorage.removeItem(ACCESS_TOKEN);
  localStorage.removeItem(EXPIRE_TIME);
  localStorage.removeItem(HUB_ID);
  localStorage.removeItem(PROJECT_ID);
}

export { fetchBimfaceBasicInfo, removeBimfaceAccessToken };
